<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="资源投入看板" data-page-identification="h_9mndd34upl">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_hakcbtmy3p 自定义模板_44a5bx6y8o -->
            <!--          调度-->
            <a-modal
                :visible="state.dispatchVisible"
                title="调度"
                centered
                :mask-closable="false"
                :keyboard="false"
                destroy-on-close
                @cancel="cancelDispatch"
                width="520px"
                @ok="handleSumitDispatch"
                :ok-button-props="{ loading: state.dispatchLoading }"
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
            >
                <div class="form-div">
                    <a-form :model="state.dispatchForm" ref="dispatchRef" :rules="dispatchRules">
                        <a-row>
                            <!-- 区域选择 -->
                            <a-col :span="24">
                                <a-form-item label="调度区域" name="areaCode">
                                    <a-select
                                        v-model:value="state.dispatchForm.areaCode"
                                        :options="state.areaList"
                                        allow-clear
                                        show-search
                                        @change="
                                            () => {
                                                state.dispatchForm.factoryCode = undefined
                                                state.dispatchForm.productLine = undefined
                                                state.formProductLineList = []
                                                state.factoryList = []
                                            }
                                        "
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        :placeholder="selectHolder"
                                    />
                                </a-form-item>
                            </a-col>

                            <a-col :span="24">
                                <!-- 工厂选择 -->
                                <a-form-item label="调度工厂" name="factoryCode">
                                    <a-select
                                        v-model:value="state.dispatchForm.factoryCode"
                                        :options="state.factoryList"
                                        allow-clear
                                        show-search
                                        @focus="getFactoryListBySelectedArea"
                                        :placeholder="selectHolder"
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        @change="
                                            () => {
                                                state.dispatchForm.productLine = undefined
                                                state.formProductLineList = []
                                            }
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="调度产品线" name="productLine">
                                    <a-select
                                        v-model:value="state.dispatchForm.productLine"
                                        :options="state.formProductLineList"
                                        show-search
                                        @focus="getProductLineByFactory"
                                        allow-clear
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        :placeholder="selectHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="调度时间" name="dispatchDate">
                                    <a-range-picker
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                                        v-model:value="state.dispatchForm.dispatchDate"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="备注" name="description">
                                    <a-textarea
                                        v-model:value="state.dispatchForm.description"
                                        :placeholder="inputHolder"
                                        :rows="4"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          调度-->
            <!--          资源分布-->
            <a-modal
                :visible="state.peopleVisible"
                :title="state.peopleTitle"
                :mask-closable="false"
                :keyboard="false"
                @cancel="cancelPeople"
                width="1600px"
                :footer="null"
            >
                <div class="modal-top">
                    <a-radio-group v-model:value="state.modalRadioValue" @change="radioChange">
                        <a-radio-button value="资源分布">资源分布</a-radio-button>
                        <a-radio-button value="调度记录">调度记录</a-radio-button>
                    </a-radio-group>
                </div>
                <div class="table-box" v-if="state.modalRadioValue === '资源分布'">
                    <a-table
                        bordered
                        :columns="peopleColumns"
                        :data-source="state.peopleDataSource"
                        :scroll="{ x: 1500, y: 600 }"
                        :pagination="false"
                        @resizeColumn="handleResizeStoryColumn"
                    >
                        <template #bodyCell="{ record, text, column, index }">
                            <template
                                v-if="
                                    ![
                                        '产品线',
                                        '区域',
                                        '工厂',
                                        '项目阶段',
                                        '项目经理',
                                        '职能类别',
                                        '项目人数',
                                        '项目总监',
                                        '验收时间',
                                        '操作'
                                    ].includes(column.title)
                                "
                            >
                                <div
                                    class="factory-div"
                                    :style="getColorCellStyle(record, column.dataIndex, extendTitle)"
                                ></div>
                            </template>
                        </template>
                    </a-table>
                </div>
                <div class="table-box-record" v-if="state.modalRadioValue === '调度记录'">
                    <a-table
                        bordered
                        :loading="state.reportLoading"
                        :pagination="false"
                        :columns="recordColumns"
                        :data-source="state.recordDataSource"
                        :scroll="{ y: 600 }"
                        @resizeColumn="handleResizeStoryColumn"
                    />
                </div>
            </a-modal>
            <!--          资源分布-->
            <div class="body">
                <div class="top-search">
                    <a-row>
                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="区域">
                                <a-select
                                    show-search
                                    :placeholder="selectHolder"
                                    :options="state.areaList"
                                    v-model:value="state.filter.areaCode"
                                    @change="areaChange"
                                    allow-clear
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="产品线">
                                <a-select
                                    show-search
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.productLine"
                                    :options="state.productLineList"
                                    @change="
                                        () => {
                                            state.filter.milepostName = undefined
                                            state.stageList = []
                                        }
                                    "
                                    allow-clear
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>

                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="项目阶段">
                                <a-select
                                    show-search
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.milepostName"
                                    :options="state.stageList"
                                    allow-clear
                                    @focus="getMilePostList"
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="项目经理">
                                <a-select
                                    :placeholder="selectHolder"
                                    show-search
                                    v-model:value="state.filter.pmName"
                                    :options="state.allUser"
                                    allow-clear
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="状态">
                                <a-select
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.status"
                                    :options="state.statusList"
                                    allow-clear
                                    :filter-option="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" label="时间">
                                <a-range-picker
                                    style="width: 100%"
                                    :value="state.filter.dateList"
                                    :disabled-date="disabledDate"
                                    value-format="YYYY-MM-DD"
                                    @change="handleDateChange"
                                    :allowClear="false"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="2" offset="10" style="display: flex; justify-content: end; align-items: start">
                            <a-space>
                                <a-button @click="getData" type="primary">查询</a-button>
                                <a-button @click="resetData" ghost type="primary"> 重置</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </div>
                <div class="content">
                    <div class="table-top">
                        <div class="tip-title">
                            <a-radio-group v-model:value="viewRadio" button-style="solid" @change="getData">
                                <a-radio-button value="FACTORY">项目列表</a-radio-button>
                                <a-radio-button value="PM_NAME">项目经理列表</a-radio-button>
                            </a-radio-group>
                        </div>
                        <div class="top-right">
                            <div class="color-item">
                                <div class="doing"></div>
                                <div>在厂</div>
                            </div>
                            <div class="color-item">
                                <div class="to-do"></div>
                                <div>撤场</div>
                            </div>
                        </div>
                    </div>
                    <div class="table-box">
                        <a-table
                            :columns="columns"
                            :data-source="state.dataSource"
                            :scroll="{ y: state.tableHeight }"
                            bordered
                            :loading="state.tableLoading"
                            :pagination="pagination"
                            @change="handleTableChange"
                            @resizeColumn="handleResizeStoryColumn"
                        >
                            <template #bodyCell="{ record, text, column, index }">
                                <template v-if="column.dataIndex === 'pmName'">
                                    <span class="opration-text" :title="text" @click="showPeople('项目经理', record)">{{
                                        text
                                    }}</span>
                                </template>
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-button
                                        size="small"
                                        type="link"
                                        @click="handleDispatch(record)"
                                        :disabled="!state.canClick"
                                        >调度</a-button
                                    >
                                </template>
                                <template
                                    v-if="
                                        ![
                                            '产品线',
                                            '区域',
                                            '工厂',
                                            '项目阶段',
                                            '项目经理',
                                            '职能类别',
                                            '项目人数',
                                            '项目总监',
                                            '验收时间',
                                            '操作'
                                        ].includes(column.title)
                                    "
                                >
                                    <!--                                  {{text}}-->
                                    <!--                                    <div class="factory-div" :style="getColorCellStyle(record, column)"></div>-->
                                    <!--                                    <div-->
                                    <!--                                        class="factory-div"-->
                                    <!--                                        :style="{-->
                                    <!--                                            backgroundColor: getColor(text)-->
                                    <!--                                        }"-->
                                    <!--                                    ></div>-->
                                    <div
                                        class="factory-div"
                                        :style="getColorCellStyle(record, column.dataIndex, extendTitle)"
                                    ></div>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>
            <!-- end vid_hakcbtmy3p 自定义模板_44a5bx6y8o -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        setCurrentMonthRange()
        getData()
        getAllUser()
        getAreaList()
        getProductLineList()
        getPression()
    })
    const headerOffset = ref(240)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }

    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    const setCurrentMonthRange = () => {
        const startOfMonth = dayjs().startOf('month').format('YYYY-MM-DD')
        const endOfMonth = dayjs().endOf('month').format('YYYY-MM-DD')
        state.filter.dateList = [startOfMonth, endOfMonth]
    }
    const state = reactive({
        filter: {
            productLine: undefined,
            areaCode: undefined,
            milepostName: undefined,
            pmName: undefined,
            status: undefined,
            dateList: []
        },
        productLineList: [],
        formProductLineList: [],
        areaList: [],
        stageList: [],
        userList: [],
        statusList: [
            {
                label: '在厂',
                value: 0
            },
            {
                label: '撤场',
                value: 1
            }
        ],
        allUser: [],
        dataSource: [],
        peopleVisible: false,
        peopleDataSource: [],
        // 调度记录
        recordColumns: [],
        peopleTitle: '项目经理',
        modalRadioValue: '资源分布',
        dispatchVisible: false,
        dispatchLoading: false,
        dispatchForm: {
            productLine: undefined,
            areaCode: undefined,
            factoryCode: undefined,
            description: undefined,
            dispatchDate: []
        },
        tableHeight: 520,
        areaFactoryList: [],
        tableLoading: false,
        canClick: false
    })
    function areaChange() {
        state.filter.milepostName = undefined
    }
    function getPression() {
        get('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/check_project_director').then(data => {
            state.canClick = data.data
        })
    }
    function getMilePostList() {
        if (!state.filter.productLine) {
            state.stageList = []
            message.info('请先选择产品线！')
            return
        }
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/project_stage_list/${state.filter.productLine}`
        ).then(data => {
            state.stageList = data.data.map(item => {
                return {
                    label: item,
                    value: item
                }
            })
        })
    }
    function getAllUser() {
        get('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/project_manager_list').then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.allUser = data.data.map(item => {
                return {
                    label: item,
                    value: item
                }
            })
        })
    }
    const baseColumns = [
        {
            title: '区域',
            dataIndex: 'areaName',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: ({ areaRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    },
                    rowSpan: areaRowSpan
                }
            }
        },
        {
            title: '工厂',
            dataIndex: 'factoryName',
            align: 'left',
            fixed: 'left',
            width: 100,
            resizable: true,
            ellipsis: true,
            customCell: ({ factoryRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    },
                    rowSpan: factoryRowSpan
                }
            }
        },
        {
            title: '产品线',
            dataIndex: 'productLine',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: ({ productLineRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '职能类别',
            dataIndex: 'functionalCategory',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目经理',
            dataIndex: 'pmName',
            align: 'left',
            fixed: 'left',
            resizable: true,
            width: 100,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            align: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目人数',
            dataIndex: 'projectParticipantNum',
            align: 'left',
            ellipsis: true,
            width: 100,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目总监',
            dataIndex: 'projectDirector',
            align: 'left',
            ellipsis: true,
            width: 100,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        }
    ]
    const pmBaseColumns = [
        {
            title: '区域',
            dataIndex: 'areaName',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: ({ areaRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    },
                    rowSpan: areaRowSpan
                }
            }
        },
        {
            title: '项目经理',
            dataIndex: 'pmName',
            align: 'left',
            fixed: 'left',
            width: 120,
            ellipsis: true,
            resizable: true,
            customCell: ({ pmRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    },
                    rowSpan: pmRowSpan
                }
            }
        },
        {
            title: '工厂',
            dataIndex: 'factoryName',
            align: 'left',
            fixed: 'left',
            width: 100,
            resizable: true,
            ellipsis: true,
            customCell: ({ factoryRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    },
                    rowSpan: factoryRowSpan
                }
            }
        },
        {
            title: '产品线',
            dataIndex: 'productLine',
            align: 'left',
            fixed: 'left',
            resizable: true,
            width: 100,
            ellipsis: true,
            customCell: ({ productLineRowSpan }) => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '职能类别',
            dataIndex: 'functionalCategory',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },

        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            align: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目人数',
            dataIndex: 'projectParticipantNum',
            align: 'left',
            ellipsis: true,

            width: 100,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目总监',
            dataIndex: 'projectDirector',
            align: 'left',
            ellipsis: true,
            width: 100,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        }
    ]
    const oprationColumns = {
        title: '操作',
        dataIndex: 'opration',
        align: 'center',
        width: 100,
        fixed: 'right',
        ellipsis: true,
        customCell: () => {
            return {
                style: {
                    padding: '8px 16px '
                }
            }
        }
    }
    const basePeopleColumns = [
        {
            title: '项目经理',
            dataIndex: 'pmName',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },

        {
            title: '产品线',
            dataIndex: 'productLine',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '区域',
            dataIndex: 'areaName',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '工厂',
            dataIndex: 'factoryName',
            align: 'left',
            fixed: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '项目阶段',
            dataIndex: 'milepostName',
            align: 'left',
            width: 100,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        }
    ]
    const peopleColumns = ref([])
    const recordColumns = ref([
        {
            title: '项目经理',
            dataIndex: 'pmName',
            align: 'left',
            width: 150,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '调度时间',
            dataIndex: 'dispatchStartDate',
            align: 'left',
            width: 150,
            ellipsis: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '调度区域',
            dataIndex: 'dispatchAreaName',
            align: 'left',
            width: 150,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '调度工厂',
            dataIndex: 'dispatchFactoryName',
            align: 'left',
            width: 150,
            ellipsis: true,
            resizable: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '调度人',
            dataIndex: 'createdBy',
            align: 'left',
            ellipsis: true,
            width: 150,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },
        {
            title: '审核人',
            dataIndex: 'updateBy',
            align: 'left',
            ellipsis: true,
            width: 150,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        },

        {
            title: '备注',
            dataIndex: 'description',
            align: 'left',
            width: 150,
            ellipsis: true,
            customCell: () => {
                return {
                    style: {
                        padding: '8px 16px '
                    }
                }
            }
        }
    ])

    const getData = () => {
        state.tableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/search', {
            ...state.filter,
            orderType: viewRadio.value,
            pageNo: 1
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                getTableData(data)
                pagination.value.total = data.data.totalElements
            })
            .finally(() => {
                state.tableLoading = false
            })
    }

    const columns = ref([])
    const extendTitle = ref([])
    let fullData = []
    const getTableData = data => {
        const dynamicColumns = data.data.extendTitle.map(item => ({
            title: item,
            dataIndex: item,
            width: 110,
            customCell: () => ({
                style: { borderRight: 'none !important' }
            })
        }))
        extendTitle.value = data.data.extendTitle

        if (viewRadio.value === 'FACTORY') {
            nextTick(() => {
                columns.value = [...baseColumns, ...dynamicColumns, oprationColumns].filter(Boolean)
            })
        } else {
            nextTick(() => {
                columns.value = [...pmBaseColumns, ...dynamicColumns, oprationColumns].filter(Boolean)
            })
        }

        const formattedData = (data.data.dataList || []).map((item, index) => {
            const { extendData, ...rest } = item
            return {
                ...rest,
                ...extendData,
                key: item.id || `key-${index}-${Date.now()}`
            }
        })

        fullData = groupData(formattedData)
        updateCurrentPageData()
    }
    function updateCurrentPageData() {
        const { current, pageSize } = pagination.value
        const start = (current - 1) * pageSize
        const end = start + pageSize
        const pageData = fullData.slice(start, end)

        // 👇 关键：只对当前页做 groupData
        state.dataSource = groupData(pageData)
        console.log(state.dataSource)
    }

    import { nextTick } from 'vue'

    function groupData(data) {
        let currentProductLine = ''
        let currentMilepostName = ''
        let currentAreaName = ''
        let currentFactoryName = ''
        let currentPmName = ''
        let productLineRowSpan = 0
        let milepostRowSpan = 0
        let areaRowSpan = 0
        let factoryRowSpan = 0
        let pmRowSpan = 0

        return data.map((item, index) => {
            // 如果 productLine 变化，重置 projectRowSpan，并计算新的 rowSpan
            if (currentProductLine !== item.productLine) {
                currentProductLine = item.productLine
                productLineRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].productLine === item.productLine) {
                        productLineRowSpan++
                    } else {
                        break
                    }
                }
                item.productLineRowSpan = productLineRowSpan
            } else {
                item.productLineRowSpan = 0
            }

            // 如果 storyName 变化，重置 milepostRowSpan，并计算新的 rowSpan
            if (currentMilepostName !== item.storyName) {
                currentMilepostName = item.storyName
                milepostRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].storyName === item.storyName) {
                        milepostRowSpan++
                    } else {
                        break
                    }
                }
                item.milepostRowSpan = milepostRowSpan
            } else {
                item.milepostRowSpan = 0
            }
            // 如果 areaName 变化，重置 areaRowSpan，并计算新的 rowSpan
            if (currentAreaName !== item.areaName) {
                currentAreaName = item.areaName
                areaRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].areaName === item.areaName) {
                        areaRowSpan++
                    } else {
                        break
                    }
                }
                item.areaRowSpan = areaRowSpan
            } else {
                item.areaRowSpan = 0
            }
            // 如果 factoryName 变化，重置 factoryRowSpan，并计算新的 rowSpan
            if (currentFactoryName !== item.factoryName) {
                currentFactoryName = item.factoryName
                factoryRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].factoryName === item.factoryName) {
                        factoryRowSpan++
                    } else {
                        break
                    }
                }
                item.factoryRowSpan = factoryRowSpan
            } else {
                item.factoryRowSpan = 0
            }
            // 如果 pmName 变化，重置 pmRowSpan，并计算新的 rowSpan
            if (currentPmName !== item.pmName) {
                currentPmName = item.pmName
                pmRowSpan = 1

                for (let i = index + 1; i < data.length; i++) {
                    if (data[i].pmName === item.pmName) {
                        pmRowSpan++
                    } else {
                        break
                    }
                }
                item.pmRowSpan = pmRowSpan
            } else {
                item.pmRowSpan = 0
            }
            return item
        })
    }
    // 分页
    const pageSizeChange = (current, size) => {
        pagination.value.current = current
        pagination.value.pageSize = size
        getData()
    }
    const pageChange = (page, pageSize) => {
        pagination.value.current = page
        pagination.value.pageSize = pageSize
        getData()
    }
    const pagination = ref({
        current: 1,
        pageSize: 50,
        showSizeChanger: true,
        total: 0,
        pageSizeOptions: ['10', '20', '40', '60', '80', '100'],
        showTotal: total =>
            `共 ${total} 个项目 第 ${pagination.value.current}/${Math.ceil(total / pagination.value.pageSize)}页`
    })
    const handleTableChange = (paginationInfo, filters, sorter) => {
        pagination.value.current = paginationInfo.current
        pagination.value.pageSize = paginationInfo.pageSize
        updateCurrentPageData()
    }
    const dates = ref()
    const hackValue = ref()
    const disabledDate = current => {
        if (!dates.value || dates.value.length === 0) {
            return false
        }

        // 将 YYYY-MM-DD 字符串转为 Day.js 对象
        const start = dates.value[0] ? dayjs(dates.value[0]) : null
        const end = dates.value[1] ? dayjs(dates.value[1]) : null

        // 计算差值（确保 start/end 存在）
        const tooLate = start && current.diff(start, 'days') > 60
        const tooEarly = end && end.diff(current, 'days') > 60

        return tooEarly || tooLate
    }
    function handleDateChange(dates) {
        if (!dates || dates.length !== 2) return

        const [start, end] = dates
        const days = dayjs(end).diff(dayjs(start), 'day')
        if (days > 60) {
            message.info('日期范围不能超过 60 天，请重新选择')
            return
        }

        state.filter.dateList = dates
    }
    const currentData = ref({})
    function showPeople(type, record) {
        currentData.value = record
        getPmGante(record)
    }
    function getPmGante(record) {
        post('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/manager_search', {
            pmName: record.pmName,
            dateList: state.filter.dateList
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            getPeopleData(data)
        })
    }
    function getPeopleData(data) {
        peopleColumns.value = []
        let newColumns = data.data.extendTitle.map((item, index) => {
            return {
                title: item,
                dataIndex: item,
                width: 110,
                customCell: () => ({
                    style: { borderRight: 'none !important' }
                })
            }
        })
        extendTitle.value = data.data.extendTitle
        peopleColumns.value = [...basePeopleColumns, ...newColumns]
        const formattedData =
            (Array.isArray(data.data.dataList) ? data.data.dataList : []).map((item, index) => {
                const { extendData, ...rest } = item // 分离出 extendData 和其他字段
                return {
                    ...rest, // 保留其他字段
                    ...extendData, // 将 extendData 展开为直接字段
                    key: item.id || `key-${index}-${Date.now()}` // 如果有 id 字段，则使用 id 作为 key，否则使用索引和时间戳组合生成唯一的 key
                }
            }) || []
        state.peopleDataSource = groupData(formattedData)

        state.peopleVisible = true
    }
    function getUserGante() {}
    function cancelPeople() {
        state.peopleVisible = false
        state.modalRadioValue = '资源分布'
        currentData.value = {}
    }
    function handleDispatch(record) {
        currentData.value = record
        state.dispatchVisible = true
    }
    const dispatchRef = ref(null)
    function handleSumitDispatch() {
        dispatchRef.value.validate().then(() => {
            state.dispatchLoading = true
            post('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/dispatch', {
                ...state.dispatchForm,
                projectId: currentData.value.projectId,
                pmName: currentData.value.pmName
            })
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelDispatch()
                })
                .finally(() => {
                    state.dispatchLoading = false
                })
        })
    }
    function cancelDispatch() {
        currentData.value = {}
        state.dispatchVisible = false
        state.dispatchForm.dispatchDate = []
        state.dispatchForm.factoryCode =
            state.dispatchForm.areaCode =
            state.dispatchForm.productLine =
            state.dispatchForm.description =
                undefined
    }
    function getProductLineList() {
        get('/solution-ppm-basic-data/api/v1/product_line/all').then(data => {
            state.productLineList = data.data.map(item => {
                return {
                    label: item.productLineName,
                    value: item.productLineCode
                }
            })
        }) // 问题类型
    }
    function getProductLineByFactory() {
        if (!state.dispatchForm.factoryCode) {
            state.formProductLineList = []
            return
        }
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/${state.dispatchForm.factoryCode}/product_line_list`
        ).then(data => {
            state.formProductLineList = data.data.map(item => {
                return {
                    label: item.productLineName,
                    value: item.productLineCode
                }
            })
        }) // 问题类型
    }
    function getAreaList() {
        get('/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/area_list').then(res => {
            state.areaList = res.data.map(item => {
                return {
                    label: item.areaName,
                    value: item.areaCode
                }
            })
        })
    }

    function getFactoryListBySelectedArea() {
        if (!state.dispatchForm.areaCode) {
            state.factoryList = []
            return
        }
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/${state.dispatchForm.areaCode}/factory_list`
        ).then(data => {
            state.factoryList = data.data.map(item => {
                return {
                    label: item.factoryName,
                    value: item.factoryCode
                }
            })
        })
    }

    const colorMap = {
        true: '#ff7672',
        false: '#cfcfcf'
    }
    function getColor(input) {
        const type = typeof input === 'Boolean' && input !== null ? input : input || false
        return colorMap[type] || '#fff'
    }
    function getColorCellStyle(record, currentKey, extendTitle) {
        const colorKeys = extendTitle.filter(key => getColor(record[key]) !== '#fff')
        const firstKey = colorKeys[0]
        const lastKey = colorKeys[colorKeys.length - 1]

        const baseColor = getColor(record[currentKey])

        const borderRadiusStyle = {}

        return {
            background: baseColor,
            ...borderRadiusStyle
        }
    }

    const inputHolder = '请输入'
    const selectHolder = '请选择'
    const dispatchRules = {
        productLine: [{ required: true, message: '请选择调度产品线', trigger: ['blur', 'change'] }],
        areaCode: [{ required: true, message: '请选择区域', trigger: ['blur', 'change'] }],
        factoryCode: [{ required: true, message: '请选择工厂', trigger: ['blur', 'change'] }],
        dispatchDate: [{ required: true, message: '请选择调度时间', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '请输入备注', trigger: ['blur', 'change'] }]
    }
    function resetData() {
        const startOfMonth = dayjs().startOf('month').format('YYYY-MM-DD')
        const endOfMonth = dayjs().endOf('month').format('YYYY-MM-DD')
        state.filter.dateList = [startOfMonth, endOfMonth]
        state.filter.areaCode =
            state.filter.productLine =
            state.filter.milepostName =
            state.filter.pmName =
            state.filter.status =
                undefined
        pagination.value.current = 1
        pagination.value.pageSize = 50
        getData()
    }
    function radioChange() {
        if (state.modalRadioValue === '调度记录') {
            getDispatchReport()
        }
    }
    //     获取调度记录
    function getDispatchReport() {
        state.reportLoading = true
        post(`/solution-ppm/api/v2/built-in-system-ppm/resource_dashboard/dispatch_list`, {
            projectManager: currentData.value.pmName
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.peopleDataSource = []
                    return
                }
                state.recordDataSource = data.data
            })
            .finally(() => {
                state.reportLoading = false
            })
    }
    const viewRadio = ref('FACTORY')
    function handleResizeStoryColumn(w, col) {
        col.width = w
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 120%;
    }
    /*
    样式*/
    .body {
        height: 100%;
    }
    .top-search {
        background-color: #fff;
        padding: 16px 24px 0 24px;
        border-radius: 4px;
    }
    .content {
        height: 100%;
        background-color: #fff;
        border-radius: 4px;
        margin-top: 16px;
    }
    .table-box:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #ebf1ff;
        color: #262626;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9 !important;
        position: relative;
    }

    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 0;
        word-break: break-all;
    }
    .table-box
        :deep(
            .ant3-table.ant3-table-bordered
                > .ant3-table-container
                > .ant3-table-content
                > table
                > thead
                > tr:not(:last-child)
                > th
        ) {
        border-bottom: 1px solid #d9d9d9;
    }
    .table-box-record:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #ebf1ff;
        color: #262626;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9 !important;
        position: relative;
    }

    .table-box-record :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        padding: 0;
        word-break: break-all;
    }
    .content {
        padding: 16px 24px;
    }
    .opration-text {
        font-size: 14px;
        color: #3875ff;
        font-weight: 500;
        text-decoration: underline;
        cursor: pointer;
    }
    .modal-top {
        display: flex;
        justify-content: end;
        margin-bottom: 16px;
    }
    .modal-top :deep(.ant3-radio-button-wrapper-checked) {
        background: rgba(56, 117, 255, 0.1);
        border: 1px solid #3875ff;
    }
    .modal-top :deep(.ant3-radio-group) {
        border-radius: 0 4px 4px 0;
    }
    .form-div :deep(.ant3-form-item-label) {
        width: 100px;
    }
    .table-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }
    .top-right {
        display: flex;
        gap: 16px;
    }
    .color-item {
        display: flex;
        gap: 16px;
        align-items: center;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 400;
    }
    .doing {
        width: 30px;
        height: 12px;
        background: #ff7672;
    }
    .to-do {
        width: 30px;
        height: 12px;
        background: #cfcfcf;
    }
    .factory-div {
        width: 100%;
        height: 20px;
    }
    .reset-btn {
        color: #262626;
        background-color: #eeeeee;
        border-color: #eeeeee;
        border-radius: 4px;
    }
    .reset-btn:hover {
        background: #3875ff;
        border-color: #d9d9d9;
        color: #fff;
    }
</style>
